import sys
import pandas as pd
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QPushButton,
                             QLabel, QFileDialog, QRadioButton, QMessageBox, QTextEdit, QFontComboBox)
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtCore import Qt
from docx import Document
from docx.shared import Pt, Cm
from docx.oxml import parse_xml
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import qn
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
import os
import time


class MeetingSignGenerator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('会议台签制作工具')
        self.setWindowIcon(QIcon('./images/桌签.png'))
        self.setGeometry(200, 200, 600, 400)

        # 设置主布局
        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignTop)
        layout.setSpacing(10)
        layout.setContentsMargins(20, 20, 20, 20)  # 设置边距

        # 设置全局字体
        font = QFont("Arial", 16)
        self.setFont(font)

        # 添加标签
        self.label = QLabel('选择台签类型：')
        layout.addWidget(self.label)

        # 添加单选按钮
        self.landscape_radio = QRadioButton('横版台签')
        self.landscape_radio.setChecked(True)  # 默认选择横版台签
        self.portrait_radio = QRadioButton('竖版台签')
        layout.addWidget(self.landscape_radio)
        layout.addWidget(self.portrait_radio)

        # 添加导入按钮并设置样式
        self.import_button = QPushButton('导入Excel文件')
        self.import_button.clicked.connect(self.import_excel)
        self.import_button.setStyleSheet("background-color: #4CAF50; color: white; padding: 10px;")
        layout.addWidget(self.import_button)

        # 添加文本输入框
        self.names_input = QTextEdit()
        self.names_input.setPlaceholderText("手动输入名字，每个名字一行")
        self.names_input.setStyleSheet("font-size: 14px; padding: 5px; border: 1px solid #ccc;")
        layout.addWidget(self.names_input)

        # 添加保存路径按钮并设置样式
        self.save_path_button = QPushButton('选择保存路径并生成文件')
        self.save_path_button.clicked.connect(self.select_save_path_and_generate)
        self.save_path_button.setStyleSheet("background-color: #2196F3; color: white; padding: 10px;")
        layout.addWidget(self.save_path_button)

        self.setLayout(layout)

        # 初始化保存路径
        self.save_path = ""


    def import_excel(self):
        options = QFileDialog.Options()
        file_name, _ = QFileDialog.getOpenFileName(self, "选择Excel文件", "",
                                                   "Excel Files (*.xls *.xlsx)", options=options)
        if file_name:
            try:
                df = pd.read_excel(file_name, header=None)
                self.names = df.iloc[:, 0].dropna().tolist()
                QMessageBox.information(self, "成功", "成功导入Excel文件！")
            except Exception as e:
                QMessageBox.warning(self, "错误", f"导入文件时出错: {str(e)}")

    def select_save_path_and_generate(self):
        options = QFileDialog.Options()
        self.save_directory = QFileDialog.getExistingDirectory(self, "选择保存目录", "", options=options)
        if self.save_directory:
            timestamp = time.strftime("%Y%m%d_%H%M%S")
            self.save_path = os.path.join(self.save_directory, f"台签_{timestamp}.docx")
            
            self.generate_signs()  # 直接生成文件

    def generate_signs(self):
        if not hasattr(self, 'names'):
            # 从输入框获取名字
            self.names = self.names_input.toPlainText().strip().split('\n')
            self.names = [name.strip() for name in self.names if name.strip()]  # 去除空行

        if not self.names:
            QMessageBox.warning(self, "错误", "请先导入Excel文件或手动输入名字！")
            return

        if self.landscape_radio.isChecked():
            self.create_landscape_signs()
        elif self.portrait_radio.isChecked():
            self.create_portrait_signs()
        else:
            QMessageBox.warning(self, "错误", "请选择台签类型！")

    def set_cell_border(self, cell):
        # 创建虚线边框
        cell_borders = parse_xml(r'<w:tcBorders xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
                                 r'<w:top w:val="dashed" w:sz="4" wSpace="0" w:space="0"/>'
                                 r'<w:left w:val="dashed" w:sz="4" wSpace="0" w:space="0"/>'
                                 r'<w:bottom w:val="dashed" w:sz="4" wSpace="0" w:space="0"/>'
                                 r'<w:right w:val="dashed" w:sz="4" wSpace="0" w:space="0"/>'
                                 r'</w:tcBorders>')
        cell._element.get_or_add_tcPr().append(cell_borders)

    def create_landscape_signs(self):
        if not self.save_path:
            QMessageBox.warning(self, "错误", "请先选择保存路径！")
            return

        doc = Document()
        section = doc.sections[0]
        section.top_margin = section.bottom_margin = section.left_margin = section.right_margin = 0

        for name in self.names:
            font_size = 0
            if len(name) == 2:
                name = name[0] + '    ' + name[1]
                font_size = 170
            elif len(name) == 3:
                font_size = 170
            elif len(name) == 4:
                font_size = 140
            elif len(name) == 5:
                font_size = 120
            elif len(name) == 6:
                font_size = 100
            elif len(name) >= 7:
                QMessageBox.warning(self, "警告", f"{name} 名字过长！")
                continue
            else:
                continue
            table = doc.add_table(rows=2, cols=1)
            table.autofit = False

            for row in table.rows:
                row.height = Cm(11)

            for i in range(2):
                cell = table.cell(i, 0)
                cell.text = name
                self.set_cell_border(cell)

                paragraph = cell.paragraphs[0]
                run = paragraph.runs[0]
                run.font.name = '微软简魏碑'
                run.font.size = Pt(font_size)
                run.bold = True
                run._element.rPr.rFonts.set(qn('w:eastAsia'), '微软简魏碑')
                paragraph.paragraph_format.line_spacing = Pt(font_size)
                paragraph.paragraph_format.space_after = Pt(0)
                paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER

            for row in table.rows:
                for cell in row.cells:
                    cell._element.get_or_add_tcPr().append(parse_xml(
                        r'<w:tcMar w:top="0" w:left="0" w:right="0" w:bottom="0" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"/>'))

            doc.add_page_break()

        doc.save(self.save_path)
        QMessageBox.information(self, "成功", f"文件将保存到: {self.save_path}")


    def sort_names(self, names):
        if len(names) % 4 != 0:
            names.extend([None] * (4 - len(names) % 4))

        sorted_names = []
        for j in range(len(names) // 4):
            sorted_names.extend(names[j::len(names) // 4])
        return sorted_names
    
    def create_portrait_signs(self):
        if not self.save_path:
            QMessageBox.warning(self, "错误", "请先选择保存路径！")
            return

        doc = Document()
        section = doc.sections[0]
        section.top_margin = section.bottom_margin = section.left_margin = section.right_margin = 0

        table = doc.add_table(rows=len(self.names), cols=1)
        table.autofit = False
        for row in table.rows:
            row.height = Cm(6.95)
        font_size = 140
        sorted_names = self.sort_names(self.names)
        for index, name in enumerate(sorted_names):
            if len(name) == 2:
                name = name[0] + '    ' + name[1]
                font_size = 140
            elif len(name) == 3:
                font_size = 140
            elif len(name) == 4:
                font_size = 120
            elif len(name) == 5:
                font_size = 100
            elif len(name) == 6:
                font_size = 90
            elif len(name) >= 7:
                QMessageBox.warning(self, "警告", f"{name} 名字过长！")
                continue
            else:
                continue
            cell = table.cell(index, 0)
            cell.text = name
            self.set_cell_border(cell)

            paragraph = cell.paragraphs[0]
            run = paragraph.runs[0]
            run.font.name = '微软简魏碑'
            run.font.size = Pt(font_size)
            run.bold = True
            run._element.rPr.rFonts.set(qn('w:eastAsia'), '微软简魏碑')
            paragraph.paragraph_format.line_spacing = Pt(font_size)
            paragraph.paragraph_format.space_after = Pt(0)
            paragraph.paragraph_format.space_before = Pt(0)
            paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
            cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
            cell._element.get_or_add_tcPr().append(parse_xml(
                r'<w:tcPr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
                r'<w:textDirection w:val="tbRl"/>'
                r'<w:vertAlign w:val="center"/>'
                r'</w:tcPr>'
            ))

        for row in table.rows:
            for cell in row.cells:
                cell._element.get_or_add_tcPr().append(parse_xml(
                    r'<w:tcMar w:top="0" w:left="0" w:right="0" w:bottom="0" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"/>'))

        doc.add_page_break()

        doc.save(self.save_path)
        QMessageBox.information(self, "成功", f"文件将保存到: {self.save_path}")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MeetingSignGenerator()
    ex.show()
    sys.exit(app.exec_())
